X=imread('Lena.jpg');
X=rgb2gray(X);
x=double(X);
[C,L]=size(x);

scale = 3;
threshold = 30;

Arg = zeros( C,L,scale );
Arg2 = zeros( C,L,scale );
Mod = zeros( C,L,scale );
Mod2 = zeros( C,L,scale );
Mod_max = zeros( C,L,scale );


[A,H,V,D] = swt2(x,scale,'db3');

for i=1:scale
    for x=1:L
        for y=1:C
            Arg(y,x,i) = pi/2 - atan( V(y,x,i)/H(y,x,i) );
            
            if( Arg(y,x,i) < -pi*3/8 || Arg(y,x,i) > pi*3/8 )
                Arg2(y,x,i) = 0;
            elseif( Arg(y,x,i) >= -3*pi/8 && Arg(y,x,i) < -pi/8 )
                Arg2(y,x,i) = 1;    
            elseif( Arg(y,x,i) >= -pi/8 && Arg(y,x,i) <= pi/8 )
                Arg2(y,x,i) = 2;    
            elseif( Arg(y,x,i) > pi/8 && Arg(y,x,i) <= pi*3/8 )                
                Arg2(y,x,i) = 3;
            end
            
            Mod(y,x,i) = sqrt( V(y,x,i)^2+H(y,x,i)^2 );
        end
    end
    
    % show Mod figure
    maxvalue = max(max(Mod(:,:,i)));
    Mod2(:,:,i) = Mod(:,:,i) * 255 / maxvalue;
%     figure();
%     imshow( uint8(Mod(:,:,i) ) );
    
end
% -----------
% | \ 0|3 / |
% |1 \ | / 2|
% ---- x ----
% |2 / | \ 1|
% | / 3|0 \ |
% -----------

%    -------------
%    | 1 | 0 | 3 |
%    -------------
%    | 2 | X | 2 |
%    -------------
%    | 3 | 0 | 1 |
%    -------------


for i=1:scale
    for x=2:L-1
        for y=2:C-1
            if Arg2(y,x,i)==0
                value1 = Mod2(y-1,x,i);
                value2 = Mod2(y+1,x,i);
            elseif Arg2(y,x,i)==1
                value1 = Mod2(y-1,x-1,i);
                value2 = Mod2(y+1,x+1,i);
            elseif Arg2(y,x,i)==2
                value1 = Mod2(y,x-1,i);
                value2 = Mod2(y,x+1,i);
            elseif Arg2(y,x,i)==3
                value1 = Mod2(y-1,x+1,i);
                value2 = Mod2(y+1,x-1,i);
            end
            
            if ( (Mod2(y,x,i) >= threshold) && ( ( Mod2(y,x,i) > value1 && Mod2(y,x,i) >= value2 ) ...
                    || ( Mod2(y,x,i) >= value1 && Mod2(y,x,i) > value2 ) ) )
                Mod_max(y,x,i) = 255;
            end 
        end
    end
    
    figure();
    imshow( uint8(Mod_max(:,:,i) ) );
    
end



% 
% out = uint8(A(:,:,3))-1;
% figure();
% imshow(out);
% 
% out = uint8(H(:,:,3))-1;
% figure();
% imshow(out);
% 
% out = uint8(V(:,:,3))-1;
% figure();
% imshow(out);
% 
% out = uint8(D(:,:,3))-1;
% figure();
% imshow(out);



